package com.zhixing.common.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.zhixing.common.domain.enums.Role;
import com.zhixing.common.domain.entity.UserInfo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;

public class JwtUtil {
    private final static String SECRET_KEY = "zhixing0123456789012345678901234";
    private final static SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());

    public static String createToken(UserInfo userInfo) {
        return Jwts.builder()
                .claim("id", userInfo.getId())
                .claim("role", JSON.toJSONString(userInfo.getRole()))
                .signWith(key)
                .compact();
    }

    public static UserInfo parseToken(String token) {
        if (ObjectUtil.isEmpty(token)) throw new JwtException("未登录");
        if (!token.startsWith("Bearer ")) throw new JwtException("无效的token");
        token = token.substring(7);
        try {
            Claims claims = Jwts.parser()
                    .verifyWith(key)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
            Integer id = claims.get("id", Integer.class);
            Role role = JSON.parseObject(claims.get("role", String.class), Role.class);
            return new UserInfo(id, role);
        } catch (Exception e) {
            throw new JwtException("无效的token");
        }
    }
}
